<template>
  <div class="change-password">
    <mu-sub-header>修改密码</mu-sub-header>
    <mu-form ref="form" :model="form" class="mu-demo-form">
      <mu-form-item label="密码" prop="password" :rules="passwordRules">
        <mu-text-field v-model="form.password" type="password" prop="password"></mu-text-field>
      </mu-form-item>
      <mu-form-item label="确认密码" prop="password" :rules="passwordRules">
        <mu-text-field v-model="form.confirm" type="password" prop="password"></mu-text-field>
      </mu-form-item>
      <mu-form-item>
        <mu-button color="primary" class="confirm-button" @click="submit">确认修改密码</mu-button>
      </mu-form-item>
    </mu-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import api from '@/api'
import { encryptPassword } from '@/api/password-client'

export default {
  name: 'ChangePassword',
  data() {
    return {
      passwordRules: [
        { validate: (val) => !!val, message: '必须填写密码' },
        { validate: (val) => val.length >= 3, message: '密码长度不能少于3个字' }
      ],
      form: {
        password: '',
        confirm: ''
      }
    }
  },
  computed: {
    ...mapGetters({
      publickey: 'publickey'
    })
  },
  methods: {
    submit() {
      this.$refs.form.validate().then((result) => {
        if (result) {
          if (this.form.password !== this.form.confirm) {
            this.$toast.error('两次密码必须一致')
          } else {
            this.changePassword()
          }
        }
      })
    },
    async changePassword() {
      try {
        const payload = encryptPassword(this.publickey, this.form.password)
        await api.changeMyPassword(payload)
        this.$toast.success('密码修改成功')
        this.$emit('refresh')
      } catch (err) {
        this.$apiCatch(err)
      }
    }
  }
}
</script>

<style scoped>
.change-password {
  width: 100%;
}
.confirm-button {
  margin: 0 auto;
}
.is-phone .change-password {
  width: 100%;
  padding: 12px;
}
.is-phone .confirm-button {
  margin: 0 auto;
}
</style>
